package com.houhanzhi.controller;


import com.houhanzhi.controller.request.ShortLinkAddRequest;
import com.houhanzhi.controller.request.ShortLinkDelRequest;
import com.houhanzhi.controller.request.ShortLinkPageRequest;
import com.houhanzhi.controller.request.ShortLinkUpdateRequest;
import com.houhanzhi.response.JsonData;
import com.houhanzhi.service.ShortLinkService;
import com.houhanzhi.vo.ShortLinkVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author houhanzhi
 * @since 2025-02-26
 */
@RestController
@RequestMapping("/api/link/v1")
public class ShortLinkController {

    @Autowired
    private ShortLinkService shortLinkService;

    @Value("${rpc.token}")
    private String rpcToken;

    /**
     * 生产者：创建短链
     *
     * @param request
     * @return
     */
    @PostMapping("/add")
    public JsonData createShortLink(@RequestBody ShortLinkAddRequest request) {
        return shortLinkService.createShortLink(request);
    }

    /**
     * 生产者：删除短链
     *
     * @param request
     * @return
     */
    @PostMapping("/del")
    public JsonData delShortLink(@RequestBody ShortLinkDelRequest request) {
        return shortLinkService.delShortLink(request);
    }

    /**
     * 生产者：更新短链
     *
     * @param request
     * @return
     */
    @PostMapping("/update")
    public JsonData updateShortLink(@RequestBody ShortLinkUpdateRequest request) {
        return shortLinkService.updateShortLink(request);
    }

    /**
     * B端：分页查找短链
     * @param request
     * @return
     */
    @PostMapping("/page")
    public JsonData pageByGroupId(@RequestBody ShortLinkPageRequest request) {
        Map<String, Object> pageResult = shortLinkService.pageByGroupId(request);
        return JsonData.buildSuccess(pageResult);
    }

    /**
     * rpc调用获取短链信息
     *
     * @return
     */
    @GetMapping(value = "/check")
    public JsonData check(@RequestParam("shortLinkCode") String shortLinkCode, HttpServletRequest request) {
        final String requestRpcToken = request.getHeader("rpc-token");
        if(rpcToken.equalsIgnoreCase(requestRpcToken)) {
            ShortLinkVO shortLinkVO = shortLinkService.parseShortLinkCode(shortLinkCode);
            return shortLinkVO == null ? JsonData.buildError("不存在") : JsonData.buildSuccess();
        }
        return JsonData.buildError("非法访问");
    }

}

